package com.rockcent.mall.controller;

import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.IDCardValidateUtil;
import com.rockcent.mall.Routes;
import com.rockcent.mall.helper.UserHelper;
import com.rockcent.mall.lib.domain.Mall;
import com.rockcent.mall.lib.domain.MallCertifyInfo;
import com.rockcent.mall.lib.domain.Merchant;
import com.rockcent.mall.lib.domain.MerchantCertify;
import com.rockcent.mall.lib.domain.enumclass.CertifyType;
import com.rockcent.mall.lib.domain.enumclass.MallAuditCertifyInfoStatusType;
import com.rockcent.mall.lib.domain.enumclass.MerchantStatus;
import com.rockcent.mall.lib.dto.LocationDto;
import com.rockcent.mall.lib.dto.MallCertifyInfoDTO;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.LocationHelper;
import com.rockcent.mall.lib.helper.MallCertifyInfoHelper;
import com.rockcent.mall.lib.repository.MallCertifyInfoRepository;
import com.rockcent.mall.lib.repository.MallRepository;
import com.rockcent.mall.lib.repository.MerchantCertifyRepository;
import com.rockcent.mall.lib.repository.MerchantRepository;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Marco on 16-11-13.
 * 平台资质信息
 */
@RestController
public class MallCertifyInfoController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MallCertifyInfoController.class);

    @Autowired
    private UserHelper userHelper;

    @Autowired
    MallCertifyInfoRepository mallCertifyInfoRepository;

    @Autowired
    MallCertifyInfoHelper mallCertifyInfoHelper;

    @Autowired
    MallRepository mallRepository;

    @Autowired
    LocationHelper locationHelper;

    @Autowired
    private MerchantCertifyRepository merchantCertifyRepository;

    @Autowired
    private MerchantRepository merchantRepository;

    /**
     * @api {POST} /mall/certifyinfo/save 资质信息保存
     * @apiGroup MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} companyName 公司名
     * @apiParam {String} organizationCode 组织机构代码
     * @apiParam {String} businessLicenseElectronic 营业执照副本电子版
     * @apiParam {String} industry 经营行业
     * @apiParam {String} nameOfCompanyLegal 法人代表姓名
     * @apiParam {String} idCardNumber 身份证号码
     * @apiParam {String} idCardNumberElectronic 法人身份证电子版
     * @apiParam {String} bankAccountName 银行开户名
     * @apiParam {String} bankAccount 公司银行账号
     * @apiParam {String} bankName 开户银行支行名称
     * @apiParam {String} bankSerialNum 开户银行支行联行号
     * @apiParam {String} bankPermitElectronic 开户银行许可证电子版
     * @apiParam {Long} locationId 开户银行所在地id
     * @apiParam {Long} companyLocationId 公司所在地id
     *
     * @apiSuccess {String} companyName 公司名
     * @apiSuccess {String} organizationCode 组织机构代码
     * @apiSuccess {String} businessLicenseElectronic 营业执照副本电子版
     * @apiSuccess {String} industry 经营行业
     * @apiSuccess {String} nameOfCompanyLegal 法人代表姓名
     * @apiSuccess {String} idCardNumber 身份证号码
     * @apiSuccess {String} idCardNumberElectronic 法人身份证电子版
     * @apiSuccess {String} bankAccountName 银行开户名
     * @apiSuccess {String} bankAccount 公司银行账号
     * @apiSuccess {String} bankName 开户银行支行名称
     * @apiSuccess {String} bankSerialNum 开户银行支行联行号
     * @apiSuccess {String} bankPermitElectronic 开户银行许可证电子版
     * @apiSuccess {Long} locationId 开户银行所在地id
     * @apiSuccess {Long} companyLocationId 公司所在地id
     * @apiSuccess {Long} mallId 平台id
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     * "version": 0,
     * "companyName": "广州乐宸",
     * "organizationCode": "35rete564654",
     * "businessLicenseElectronic": "http://uploads.rockcent.com/20160803/201608031045227nndznhk.png",
     * "industry": "网络技术的研究",
     * "nameOfCompanyLegal": "黄乐钊",
     * "idCardNumber": "440802197604020417",
     * "idCardNumberElectronic": "http://uploads.rockcent.com/20160803/20160803105206E1aWhuYT.png",
     * "bankAccountName": "广州乐"
     * "bankAccount": "120908294410333",
     * "bankName": "招商银行股份有限公司广州金穗支行",
     * "bankSerialNum": "120908294410333",
     * "bankPermitElectronic": "http://uploads.rockcent.com/20160803/20160803105411LyAFthv6.jpg",
     * "mallId": 1,
     * "locationId": 120103,
     * "companyLocationId":120103
     * }
     * }
     */
    @RequestMapping(value = Routes.MALL_CERTIFYINFO_SAVE, method = RequestMethod.POST)
    public JsonResult save(@RequestBody MallCertifyInfoDTO mallCertifyInfoDTO, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {

            MallCertifyInfo info = mallCertifyInfoRepository.findByMallId(userInfoDto.mall.getId());
            if(info != null) {
                jsonResult.remind("平台资质信息已存在,请不要重复添加",log);
                return;
            }

            //验证参数合法性
            boolean isPass = checkMallCertifyInfo(mallCertifyInfoDTO,jsonResult);
            if(!isPass) {
                return;
            }

            mallCertifyInfoDTO.setMallId(userInfoDto.mall.getId());
            info = new MallCertifyInfo();
            BeanUtils.copyProperties(info, mallCertifyInfoDTO);
            info = mallCertifyInfoRepository.save(info);

            // 完善B端认证信息
            MerchantCertify merchantCertify = merchantCertifyRepository.findByUserInfoIdAndMallId(userInfoDto.getId(), info.getMallId());
            if (merchantCertify != null) {
                merchantCertify.setIdcardCode(info.getIdCardNumber());
                merchantCertify.setType(CertifyType.COMPANY);
                merchantCertify.setRealName(info.getNameOfCompanyLegal());
                merchantCertify.setIdCardPicUrl(info.getIdCardNumberElectronic());
                merchantCertifyRepository.save(merchantCertify);
            }

            //完善平台信息后平台才认证通过
            Mall mall = mallRepository.findById(userInfoDto.mall.getId());
            if(mall!=null && Whether.NO.equals(mall.getAuditValidate())) {
                mall.setAuditCertifyInfoStatus(MallAuditCertifyInfoStatusType.AUDIT);
                mallRepository.save(mall);
            }

            //完善平台信息后商家才认证通过
            Merchant merchant = merchantRepository.findByMallId(info.getMallId());
            if(merchant!=null && MerchantStatus.UNVERIFY.equals(merchant.getStatus())) {
                merchant.setStatus(MerchantStatus.VERIFIED);
                merchantRepository.save(merchant);
            }

            jsonResult.data = info;
        };
        return doing.go(request, log);

    }

    /**
    * @api {GET} /mall/certifyinfo/info 资质信息详情
    * @apiGroup MALL
    * @apiVersion 1.0.0
    * @apiHeader {String} userToken 用户token
    * @apiHeader {String} domain 请求域名
    *
    * @apiSuccess {String} companyName 公司名称
    * @apiSuccess {String} organizationCode 组织机构代码
    * @apiSuccess {String} businessLicenseElectronic 营业执照副本电子版
    * @apiSuccess {String} industry 经营行业
    * @apiSuccess {String} nameOfCompanyLegal 法人代表姓名
    * @apiSuccess {String} idCardNumber 身份证号码
    * @apiSuccess {String} idCardNumberElectronic 法人身份证电子版
     *@apiSuccess {String} bankAccountName 银行开户名
    * @apiSuccess {String} bankAccount 公司银行账号
    * @apiSuccess {String} bankName 开户银行支行名称
    * @apiSuccess {String} bankSerialNum 开户银行支行联行号
    * @apiSuccess {String} bankPermitElectronic 开户银行许可证电子版
    * @apiSuccess {Long} locationId 开户银行所在地id
    * @apiSuccess {Long} proviceId 开户银行所在省份
    * @apiSuccess {Long} cityId 开户银行所在市
    * @apiSuccess {Long} zoneId 开户银行所在区
    * @apiSuccess {Long} companyLocationId 公司所在地id
    * @apiSuccess {Long} companyProviceId 公司所在省份
    * @apiSuccess {Long} companyCityId 公司所在市
    * @apiSuccess {Long} companyZoneId 公司所在区
    * @apiSuccess {Long} mallId 平台id
    *
    * @apiSuccessExample {json} Success-Response:
    * {
    * "code": "1",
    * "desc": "成功",
    * "data": {
    * "version": 0,
    * "companyName": "广州乐宸网络科技有限公司",
    * "organizationCode": "35rete564654",
    * "businessLicenseElectronic": "http://uploads.rockcent.com/20160803/201608031045227nndznhk.png",
    * "industry": "网络技术的研究",
    * "nameOfCompanyLegal": "黄乐钊",
    * "idCardNumber": "440802197604020417",
    * "idCardNumberElectronic": "http://uploads.rockcent.com/20160803/20160803105206E1aWhuYT.png",
    * "bankAccountName": "广州乐宸",
    * "bankAccount": "120908294410333",
    * "bankName": "招商银行股份有限公司广州金穗支行",
    * "bankSerialNum": "120908294410333",
    * "bankPermitElectronic": "http://uploads.rockcent.com/20160803/20160803105411LyAFthv6.jpg",
    * "mallId": 1,
    * "locationId": 440105,
    * "proviceId": 440000,
    * "cityId": 440100,
    * "zoneId": 440105,
    * "companyLocationId": 440105,
    * "companyProviceId": 440000,
    * "companyCityId": 440100,
    * "companyZoneId": 440105
    * }
    * }
    */
    @RequestMapping(value = Routes.MALL_CERTIFYINFO_INFO, method = RequestMethod.GET)
    public JsonResult info(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            if(mall==null) {
                jsonResult.remind("mall记录不存在",log);
                return;
            }
            MallCertifyInfoDTO mallCertifyInfoDTO = new MallCertifyInfoDTO();
            MallCertifyInfo mallCertifyInfo = mallCertifyInfoRepository.findByMallId(userInfoDto.mall.getId());
            if(mallCertifyInfo==null) {
                mallCertifyInfo = new MallCertifyInfo();
            } else {
                //开户银行所在地
                if(mallCertifyInfo.getLocationId()!=null) {
                    LocationDto locationDto = locationHelper.getFullLocation(mallCertifyInfo.getLocationId());
                    if (locationDto != null) {
                        mallCertifyInfoDTO.setProviceId(locationDto.getProviceId());
                        mallCertifyInfoDTO.setCityId(locationDto.getCityId());
                        mallCertifyInfoDTO.setZoneId(locationDto.getId());
                    }
                }
                //公司所在地
                if(mallCertifyInfo.getCompanyLocationId()!=null) {
                    LocationDto companyLocationDto = locationHelper.getFullLocation(mallCertifyInfo.getCompanyLocationId());
                    if (companyLocationDto != null) {
                        mallCertifyInfoDTO.setCompanyProviceId(companyLocationDto.getProviceId());
                        mallCertifyInfoDTO.setCompanyCityId(companyLocationDto.getCityId());
                        mallCertifyInfoDTO.setCompanyZoneId(companyLocationDto.getId());
                    }
                }
            }
            BeanUtils.copyProperties(mallCertifyInfoDTO, mallCertifyInfo);
            mallCertifyInfoDTO.setCompanyName(mall.getCompanyName());
            jsonResult.data = mallCertifyInfoDTO;
        };
        return doing.go(request, log);
    }

    /**
     * @api {PUT} /mall/certifyinfo/update 资质信息更新
     * @apiGroup MALL
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     *
     * @apiParam {String} companyName 公司名
     * @apiParam {String} organizationCode 组织机构代码
     * @apiParam {String} businessLicenseElectronic 营业执照副本电子版
     * @apiParam {String} industry 经营行业
     * @apiParam {String} nameOfCompanyLegal 法人代表姓名
     * @apiParam {String} idCardNumber 身份证号码
     * @apiParam {String} idCardNumberElectronic 法人身份证电子版
     * @apiParam {String} bankAccountName 银行开户名
     * @apiParam {String} bankAccount 公司银行账号
     * @apiParam {String} bankName 开户银行支行名称
     * @apiParam {String} bankSerialNum 开户银行支行联行号
     * @apiParam {String} bankPermitElectronic 开户银行许可证电子版
     * @apiParam {Long} locationId 开户银行所在地id
     * @apiParam {Long} companyLocationId 公司所在地id
     *
     * @apiSuccess {String} companyName 公司名
     * @apiSuccess {String} organizationCode 组织机构代码
     * @apiSuccess {String} businessLicenseElectronic 营业执照副本电子版
     * @apiSuccess {String} industry 经营行业
     * @apiSuccess {String} nameOfCompanyLegal 法人代表姓名
     * @apiSuccess {String} idCardNumber 身份证号码
     * @apiSuccess {String} idCardNumberElectronic 法人身份证电子版
     * @apiSuccess {String} bankAccountName 银行开户名
     * @apiSuccess {String} bankAccount 公司银行账号
     * @apiSuccess {String} bankName 开户银行支行名称
     * @apiSuccess {String} bankSerialNum 开户银行支行联行号
     * @apiSuccess {String} bankPermitElectronic 开户银行许可证电子版
     * @apiSuccess {Long} locationId 开户银行所在地id
     * @apiSuccess {Long} companyLocationId 公司所在地id
     * @apiSuccess {Long} mallId 平台id
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     * "companyName": "test",
     * "organizationCode": "35rete564654",
     * "businessLicenseElectronic": "http://uploads.rockcent.com/20160803/201608031045227nndznhk.png",
     * "industry": "网络技术的研究",
     * "nameOfCompanyLegal": "黄乐钊",
     * "idCardNumber": "440802197604020417",
     * "idCardNumberElectronic": "http://uploads.rockcent.com/20160803/20160803105206E1aWhuYT.png",
     * "bankAccountName": "test",
     * "bankAccount": "120908294410333",
     * "bankName": "招商银行股份有限公司广州金穗支行",
     * "bankSerialNum": "120908294410333",
     * "bankPermitElectronic": "http://uploads.rockcent.com/20160803/20160803105411LyAFthv6.jpg",
     * "mallId": 1,
     * "locationId": 120103,
     * "companyLocationId":120103
     * }
     * }
     */
    @RequestMapping(value = Routes.MALL_CERTIFYINFO_UPATE, method = RequestMethod.PUT)
    public JsonResult update(@RequestBody MallCertifyInfoDTO mallCertifyInfoDTO, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            Mall mall = mallRepository.findOne(userInfoDto.mall.getId());
            if(mall==null) {
                jsonResult.remind("mall记录不存在",log);
                return;
            }
            //验证参数合法性
            boolean isPass = checkMallCertifyInfo(mallCertifyInfoDTO,jsonResult);
            if(!isPass) {
                return;
            }
            MallCertifyInfo mallCertifyInfo = mallCertifyInfoRepository.findByMallId(userInfoDto.mall.getId());
            if(mallCertifyInfo==null) {
                jsonResult.remind("资质信息记录不存在",log);
                return;
            }
            mallCertifyInfo.setCompanyName(mallCertifyInfoDTO.getCompanyName());
            mallCertifyInfo.setOrganizationCode(mallCertifyInfoDTO.getOrganizationCode());
            mallCertifyInfo.setBusinessLicenseElectronic(mallCertifyInfoDTO.getBusinessLicenseElectronic());
            mallCertifyInfo.setIndustry(mallCertifyInfoDTO.getIndustry());
            mallCertifyInfo.setNameOfCompanyLegal(mallCertifyInfoDTO.getNameOfCompanyLegal());
            mallCertifyInfo.setIdCardNumber(mallCertifyInfoDTO.getIdCardNumber());
            mallCertifyInfo.setIdCardNumberElectronic(mallCertifyInfoDTO.getIdCardNumberElectronic());
            mallCertifyInfo.setBankAccountName(mallCertifyInfoDTO.getBankAccountName());
            mallCertifyInfo.setBankAccount(mallCertifyInfoDTO.getBankAccount());
            mallCertifyInfo.setBankName(mallCertifyInfoDTO.getBankName());
            mallCertifyInfo.setBankSerialNum(mallCertifyInfoDTO.getBankSerialNum());
            mallCertifyInfo.setBankPermitElectronic(mallCertifyInfoDTO.getBankPermitElectronic());
            mallCertifyInfo.setLocationId(mallCertifyInfoDTO.getLocationId());
            mallCertifyInfo.setCompanyLocationId(mallCertifyInfoDTO.getCompanyLocationId());
            mallCertifyInfoRepository.save(mallCertifyInfo);
            mall.setCompanyName(mallCertifyInfoDTO.getCompanyName());
            mall.setAuditCertifyInfoStatus(MallAuditCertifyInfoStatusType.AUDIT);
            mallRepository.save(mall);
            jsonResult.data = mallCertifyInfo;
        };
        return doing.go(request, log);

    }

    private boolean checkMallCertifyInfo(MallCertifyInfoDTO mallCertifyInfoDTO, JsonResult jsonResult) {
        //公司名
        if (StringUtils.isBlank(mallCertifyInfoDTO.getCompanyName())) {
            jsonResult.remind("公司名 不能为空",log);
            return false;
        }
        //组织机构代码
        if (StringUtils.isBlank(mallCertifyInfoDTO.getOrganizationCode())) {
            jsonResult.remind("组织机构代码 不能为空",log);
            return false;
        }
        //营业执照副本电子版
        if (StringUtils.isBlank(mallCertifyInfoDTO.getBusinessLicenseElectronic())) {
            jsonResult.remind("营业执照副本电子版 不能为空",log);
            return false;
        }
        //所在地区
        if (mallCertifyInfoDTO.getCompanyLocationId()==null) {
            jsonResult.remind("公司所在地区 不能为空",log);
            return false;
        }
        //经营行业
        if (StringUtils.isBlank(mallCertifyInfoDTO.getIndustry())) {
            jsonResult.remind("经营行业 不能为空",log);
            return false;
        }
        //法人代表姓名
        if (StringUtils.isBlank(mallCertifyInfoDTO.getNameOfCompanyLegal())) {
            jsonResult.remind("法人代表姓名 不能为空",log);
            return false;
        }
        //身份证号码
        if (StringUtils.isBlank(mallCertifyInfoDTO.getIdCardNumber())) {
            jsonResult.remind("身份证号码 不能为空",log);
            return false;
        }
        if (!IDCardValidateUtil.isIdCardValidate(mallCertifyInfoDTO.getIdCardNumber())) {
            jsonResult.remind("身份证号码 格式不正确",log);
            return false;
        }
        //法人身份证电子版
        if (StringUtils.isBlank(mallCertifyInfoDTO.getIdCardNumberElectronic())) {
            jsonResult.remind("法人身份证电子版 不能为空",log);
            return false;
        }
        //银行开户名
        if (StringUtils.isBlank(mallCertifyInfoDTO.getBankAccountName())) {
            jsonResult.remind("银行开户名 不能为空",log);
            return false;
        }
        //公司银行账号
        if (StringUtils.isBlank(mallCertifyInfoDTO.getBankAccount())) {
            jsonResult.remind("公司银行账号 不能为空",log);
            return false;
        }
        //开户银行支行名称
        if (StringUtils.isBlank(mallCertifyInfoDTO.getBankName())) {
            jsonResult.remind("开户银行支行名称 不能为空",log);
            return false;
        }
        //开户银行支行联行号
        if (StringUtils.isBlank(mallCertifyInfoDTO.getBankSerialNum())) {
            jsonResult.remind("开户银行支行联行号 不能为空",log);
            return false;
        }
        //开户银行许可证电子版
        if (StringUtils.isBlank(mallCertifyInfoDTO.getBankPermitElectronic())) {
            jsonResult.remind("开户银行许可证电子版 不能为空",log);
            return false;
        }
        //开户银行所在地
        if (mallCertifyInfoDTO.getLocationId() == null) {
            jsonResult.remind("开户银行所在地 不能为空",log);
            return false;
        }
        return true;
    }
}